package com.hc.web.service.bbs;

import java.util.List;
import java.util.Iterator;
import java.io.FileOutputStream;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import com.hc.entity.bbs.BBSComponent;
import com.hc.entity.bbs.Topic;
import com.hc.entity.bbs.Reply;
import com.hc.dao.bbs.ClubDAO;
import com.hc.dao.bbs.TopicDAO;
import com.hc.dao.bbs.ReplyDAO;
import com.hc.dao.security.UserDetailsDAO;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
import org.jdom.output.Format;
import com.hc.entity.common.Page;
import com.hc.util.CommonUtils;

import org.springframework.security.userdetails.UserDetails;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ClubService {
	private ClubDAO clubDAO;
	private TopicDAO topicDAO;
	private ReplyDAO replyDAO;
	private UserDetailsDAO userDetailsDAO;
    private Log log;
	
    public ClubService() {
    	this.log = LogFactory.getLog(this.getClass());
    }
    
	public void setClubDAO(ClubDAO clubDAO) {
		this.clubDAO = clubDAO;
	}
	
	public void setTopicDAO(TopicDAO topicDAO) {
		this.topicDAO = topicDAO;
	}
	
	public void setReplyDAO(ReplyDAO replyDAO) {
		this.replyDAO = replyDAO;
	}

	public void createXmlForClub() {
		List<BBSComponent> list = clubDAO.loadAll();
		Element root = new Element("club");
		BBSComponent member;
		for (int i = 0; i < list.size(); i++) {
			member = list.get(i);
			Element element = new Element(member.getComponentType());
			element.setAttribute("name", member.getComponentName());
			element.setAttribute("parentId", member.getParentId().toString());
			element.setAttribute("componentId", member.getComponentId()
					.toString());
			root.addContent(element);
		}

		// 创建根节点，参数为根元素
		Document doc = new Document(root);
		// 创建XML输出对象
		XMLOutputter outer = new XMLOutputter();
		// 创建输出格式对象
		Format format = Format.getPrettyFormat();
		// 输出格式的缩进字符为两个空格
		format.setIndent("  ");
		try {
			// 因为输出内容中含有汉字，所以输出格式的字符编码应设为GB2312
			format.setEncoding("UTF-8");
			// 为XML输出对象指定输出格式
			outer.setFormat(format);
			// 创建写文件对象
			String path = System.getProperty("user.dir").replaceFirst("bin.*$", "") + "/webapps/HundredCards/pages/bbs/club.xml";
			FileOutputStream out = new FileOutputStream(path);
			// 将根节点输出到XML文档
			outer.output(doc, out);
			// 关闭输出流
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
    
	public Topic getTopicByTopicId(Integer topicId) {
	    Topic topic = null;
	    topic = topicDAO.getEntityById(topicId);
	    for (Reply reply : topic.getChildren()) {
	    	reply.setFormattedDate(CommonUtils.formatDateTime(reply.getReplyDate()));
	    }
	    return topic;
	}
	
	public BBSComponent getBBSComponentByComponentId(Integer componentId) {
		return clubDAO.getEntityById(componentId);
	}
	
	public String getAncestorPath(Object object, String base) {
		BBSComponent parent = clubDAO.getParent(object);
		String basePath = base;
		if ((object instanceof BBSComponent) && ((BBSComponent) object).getComponentType().equalsIgnoreCase("forum") == false) {
			basePath = getAncestorPath(parent, parent.getComponentName() + " -> " + basePath);
		}
		return basePath;
	}
	
	public Page findTopicPageByCriteria(int pageSize, int componentId, int pageNo) {
		//Detect the page no should be in approciate scope.
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Topic.class);
		detachedCriteria.add(Restrictions.eq("parentId",new Integer(componentId)));
		int pageCount = (clubDAO.getCount(detachedCriteria) + pageSize - 1) / pageSize;
		if (pageCount == 0) {
			return null;
		}
			
		if (pageNo <= 0) {
			pageNo = 1;
		} else if (pageNo > pageCount) {
			pageNo = pageCount;
		}
		Page page = clubDAO.findPageByCriteria(detachedCriteria, pageSize, pageNo);
		for (Iterator<Topic> iterator = page.getEntityList().iterator(); iterator.hasNext();) { 
			Topic topic = (Topic) iterator.next();
			topic.setFormattedDate(CommonUtils.formatDateTime(topic.getTopicDate()));
			if (topic.getChildren().size() > 0) {
				Reply lastReplier = (Reply)topic.getChildren().toArray()[topic.getChildren().size()-1];
				topic.setLastReplier(lastReplier.getReplyAuthor());
			} else {
				topic.setLastReplier("----");
			}
		}
		return page;
	}
	
	public BBSComponent getParent(Object object) {
		return clubDAO.getParent(object);
	}
	
	public int getTopicCountByComponentId(Integer componentId) {
		return clubDAO.getTopicCountByComponentId(componentId);
	}
	
	public void saveTopic(Topic topic) {
        topic.setTopicAuthor(CommonUtils.getCurrentUsername());
		topicDAO.save(topic);
	}
	
	public void saveReply(Reply reply) {
		reply.setReplyAuthor(CommonUtils.getCurrentUsername());
		log.debug("currentUsername = " + CommonUtils.getCurrentUsername());
		replyDAO.save(reply);
	}
	
	public UserDetails getUserDetailsByUsername(String username) {
		return userDetailsDAO.getEntityById(username);
	}
}
